import {
	getTableOperate,
	getTableAggregate,
	getTableCommand
} from '@/utils/cloudDatabaseUtil.js'
import storageUtil from '@/utils/storageUtil.js'
import toastUtil from '@/utils/toastUtil.js'
import {
	getDate,
	getYear,
	getMonth,
	getDay,
	getHour,
	getMinute,
	getSecond
} from '@/utils/dateUtil.js'

const tableName = 'weight'
/**
 * 查询体重
 * @param {时间对象} date 
 */
export function findWeightPageApi(data) {

	// return getTableOperate(tableName).where({
	// }).get()

	return new Promise(function(resolve, reject) {
		getTableOperate(tableName).where({
				openId: storageUtil.getOpenId()
			})
			.orderBy("dateTime", "desc")
			.orderBy("_id", "desc")
			.skip(data.skip) // 跳过前20条
			.limit(data.pageSize) // 获取20条
			.get().then((res) => {
				// res = JSON.parse(res)
				resolve && resolve(res.result)
			}, (res) => {
				// res = JSON.parse(res)
				reject && reject(res.result)
			})
	})
}


/**
 * 新增体重
 * @param {时间对象} data 
 */
export function addWeightApi(data) {
	let openId = storageUtil.getOpenId()
	// if(!openId){
	// 	toastUtil.showToast('找不到用户信息，请刷新重试，或者联系管理员!')
	// 	return
	// }
	data.openId = openId
	return new Promise(function(resolve, reject) {

		getTableOperate(tableName).add(data).then((res) => {
			console.log("最开始新增返回值 : ", res)
			// res = JSON.parse(res)
			resolve && resolve(res.result)
		}, (res) => {
			// res = JSON.parse(res)
			console.log("最开始新增返回值 失败 : ", res)
			reject && reject(res.result)
		})
	})
}


/**
 * 查询体重
 * @param {时间对象} date 
 */
export function findWeightListApi(data) {
	let openId = storageUtil.getOpenId()
	const $ = getTableAggregate()
	const _ = getTableCommand()
	let parmDateFmt = data.date.getTime()
	console.log("parmDateFmt : ", getYear(data.date), "-", getMonth(data.date), "-", getDay(data.date))
	console.log("parmDateFmt : ", parmDateFmt)
	return new Promise(function(resolve, reject) {
		let res = getTableOperate(tableName).aggregate()
			.match({
				dateTimeStamp: _.gte(parmDateFmt),
				openId: _.eq(openId)
			})
			.group({
				_id: '$' + data.groupField,
				weight: $.first('$weight'),
				date: $.first('$date'),
				dateTime: $.first('$dateTime'),
				time: $.first('$time'),
				openid: $.first('$_openid')
			})
			.sort({
				dateTime: 1,
			})
			.skip(0)
			.limit(500) // 限制返回数量为 10 条
			.end()
			.then((res) => {
				console.log('原始体重数据返回值 : ', res)
				resolve && resolve(res.result)
			}, (res) => {
				console.log('原始体重异常数据返回值 : ', res)
				reject && reject(res.result)
			})
	})
}


/**
 * 新增体重
 * @param {时间对象} data 
 */
export function deleteWeightApi(id) {
	return new Promise(function(resolve, reject) {

		getTableOperate(tableName).doc(id).remove().then((res) => {
			console.log("删除返回值 : ", res)
			// res = JSON.parse(res)
			resolve && resolve(res.result)
		}, (res) => {
			// res = JSON.parse(res)
			reject && reject(res.result)
		})
	})
}

